import django.shortcuts as sc
import ourcity.reps.cicero_lookup as lookup

from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.template.loader import get_template

from ourcity.reps import models
from ourcity.core.models import Profile

def index(request):
    context = RequestContext(request)
    # post disabled for now
    #if request.method == 'POST':
    #    address = request.POST.get('address')
    #    if address:
    #        profile = request.user.get_profile()
    #        profile.address = address
    #        profile.city = 'Philadelphia'
    #        profile.state = 'PA'
    #        try:
    #            reps = lookup.get_reps(address)
    #        except lookup.NoAddressMatch:
    #            reps = []
    #        except lookup.ConnectionError:
    #            reps = []
    #        profile.reps.clear()
    #        for rep in reps:
    #            profile.reps.add(rep)
    #        profile.save()
    #        return HttpResponseRedirect(reverse('reps'))
    address = request.GET.get('address')
    districts = models.District.objects.all()
    if address:
        cc = lookup.CiceroConnection()
        location, districts = cc.query_address(address, 'Philadelphia', 'PA')
        context['get_address'] = True
        context['city_and_state'] = 'Philadelphia, PA'
    elif request.user.is_authenticated() and not request.GET.get('a'):
        try:
            profile = request.user.get_profile()
        except Profile.DoesNotExist:
            pass
        else:
            address = profile.address
            districts = profile.districts.all()
            cs_list = []
            if profile.city:
                cs_list.append(profile.city)
            if profile.state:
                cs_list.append(profile.state)
            context['city_and_state'] = ', '.join(cs_list)
    context['address'] = address
    is_reps = False
    current = None
    if districts:
        is_reps = True
        if request.GET.get('n'):
            reps = models.Representative.objects.filter(district__in=districts)
            context['reps_by_name'] = reps.order_by('last_name', 'first_name')
            current = 'by_name'
        else:
            local_reps = []
            state_reps = []
            national_reps = []
            for district in districts:
                if district.type.name.startswith('LOCAL'):
                    for rep in district.reps.active():
                        local_reps.append(rep)
                elif district.type.name.startswith('STATE'):
                    for rep in district.reps.active():
                        state_reps.append(rep)
                elif district.type.name.startswith('NATIONAL'):
                    for rep in district.reps.active():
                        national_reps.append(rep)
            type_map = {
                'LOCAL': 0,
                'LOCAL_EXEC': 1,
                'STATE_LOWER': 0,
                'STATE_UPPER': 1,
                'STATE_EXEC': 2,
                'NATIONAL_LOWER': 0,
                'NATIONAL_UPPER': 1,
                'NATIONAL_EXEC': 2,
            }
            title_map = {
                'Vice President': 0,
                'President': 1,
                'Lieutenant Governor': 0,
                'Governor': 1,
            }
            def rep_sort(reps):
                # DSU
                reps = [(
                    type_map[rep.district.type.name],
                    int(rep.district.name) if rep.district.name.isdigit() \
                        else rep.district.name,
                    title_map.get(rep.title),
                    rep.last_name,
                    rep.first_name,
                    rep,
                ) for rep in reps]
                reps.sort()
                reps = [x[-1] for x in reps]
                return reps
            context['local_reps'] = rep_sort(local_reps)
            context['state_reps'] = rep_sort(state_reps)
            context['national_reps'] = rep_sort(national_reps)
            current = 'by_level'
    context['is_reps'] = is_reps
    context['current'] = current
    template = get_template('reps/index.html')
    return HttpResponse(template.render(context))

def profile(request, id):
    context = RequestContext(request)
    rep = sc.get_object_or_404(models.Representative, id=id)
    context['rep'] = rep
    donations = models.Donation.objects.filter(representative=rep).order_by(
            '-amount')[:10]
    context['donations'] = donations
    news = rep.news.active()
    current = 'all'
    if request.GET.get('r'):
        news = rep.news.reports()
        current = 'reports'
    if request.GET.get('p'):
        news = rep.news.posts()
        current = 'posts'
    context['news'] = news
    context['current'] = current
    template = get_template('reps/profile.html')
    return HttpResponse(template.render(context))

